<?php

namespace shopend\controllers;

use common\models\Active;
use common\service\ConstantService;
use common\service\LogaddService;
use common\service\CommonService;
use common\service\GoodsService;
use common\models\Goods;
use common\models\Tree;
use common\models\GoodsImg;
use common\models\GoodsAttr;
use common\models\Activity;
use common\models\AttributeDeion;
use common\models\AttributeDesVal;
class GoodsController extends BaseController
{

    /**
     * 列表
     */
    public function actionIndex(){
        if($this->isGet() && $this->isAjax()){
            $Goods = Goods::find();
            $Goods_name = $this->get('goods_name')?$this->get('goods_name'):'';
            $tree_id = $this->get('tree_id')?$this->get('tree_id'):0;
            $two_id = $this->get('two_id')?$this->get('two_id'):0;
            $three_id = $this->get('three_id')?$this->get('three_id'):0;
            $Goods->andWhere(['is_del'=>0]);
            $Goods->andWhere(['shop_id'=>$this->shop['id']]);
            if($Goods_name){
                $Goods->andWhere(['like','goods_name',$Goods_name]);
            }
            if($tree_id){
                $Goods->andWhere(['one_tree_id'=>$tree_id]);

            }
            if($two_id){
                $Goods->andWhere(['two_tree_id'=>$two_id]);

            }
            if($three_id){
                $Goods->andWhere(['three_tree_id'=>$three_id]);
            }
            $p = intval( $this->get('page',1) );
            $p = ( $p > 0 )? $p : 1;
            $count = $Goods->count();

            $offset = ($p - 1) * $this->get('limit',2);

            $data = $Goods->select('goods_name,id,shop_id,sales_volume,status')
                ->limit($this->get('limit',10))
                ->offset($offset)
                ->orderBy(['id'=>SORT_DESC])
                ->asArray()
                ->all();
            $goodsModel = new Goods();
            $list = $goodsModel->GetgoogsList($data,1);
            return $this->renderPageJson($list,$count,ConstantService::$response_tab_success);
        }
        $trees = Tree::find()->where(['level'=>'1'])->asArray()->all();
        return $this->render('index',['trees' => $trees]);
    }

    /**
     * 添加商品
     * @return string
     */
    public function actionAdd(){
        if($this->isAjax() && $this->isPost()) {
            $data = $this->post();
            $msg = $this->_validation($data);

            if($msg != 'true'){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }
            $model = new Goods();
            $banner = $data['banner'];
            $tby = $data['tby'];
            unset($data['banner']);
            unset($data['tby']);
            $data['shop_id'] = $this->shop->id;
            $data['is_del'] = 0;
            $data['status'] = 0;
            $model->setAttributes($data);
            if($model->save()){
                //添加banner图
                $id = $model->attributes['id'];
                $newimg = [];
                for ($c = 0; $c < count($banner);$c++){
                    $imgdata = [];
                    $imgdata['goods_id'] = $id;
                    $imgdata['img_url'] = $banner[$c];
                    $imgdata['status'] = 1;
                    $imgdata['update_at'] = time();
                    $imgdata['create_at'] = time();
                    $newimg[] = $imgdata;
                }
                GoodsImg::getDb()->createCommand()->batchInsert('goods_img',['goods_id','img_url','status','update_at','create_at'],$newimg)->execute();

                $newdata = [];
                foreach ($tby as $attrlist){
                    $setattr = array();
                    $setattr['goods_id'] = $id;
                    $setattr['original_price'] = $attrlist[0];
                    $setattr['discount_price'] = $attrlist[1];
                    $setattr['inventory'] = $attrlist[2];
                    $setattr['image'] = $attrlist[3]?$attrlist[3]:$data['list_img'];
                    $setattr['attribute_value_id'] = $attrlist[4];
                    $setattr['is_del'] = 0;
                    $setattr['create_time'] = time();
                    $setattr['update_time'] = time();
                    $newdata[] = $setattr;
                }
//                //批量添加
                GoodsAttr::getDb()->createCommand()->batchInsert('goods_attr',['goods_id','original_price','discount_price','inventory','image','attribute_value_id','is_del','create_time','update_time'],$newdata)->execute();

                //商品属性
                if(!empty($data['attr_describe'])) {
                    $this->_SetGoodsAttrDes($data['attr_describe'],$id);
                }
                return $this->renderJson([],'新增成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'新增失败',ConstantService::$response_fail);
        }
        $trees = Tree::find()->where(['level'=>'1'])->asArray()->all();
        return $this->render('add',[
        'trees' => $trees,]);
    }



    /**
     * 修改商品
     */
    public function actionUpdate(){
        if($this->isAjax() && $this->isPost()) {
            $data = $this->post();
            $id = $data['goods_id'];
            //验证是否当前商家
            $is_shop = Goods::find()->where(['id' => $id, 'shop_id' => $this->shop->id])->asArray()->one();
            if(!$is_shop){
                return $this->renderJson([],'没有此商品',ConstantService::$response_fail);
            }

            $msg = $this->_validation($data);
            if($msg != 'true'){
                return $this->renderJson([],$msg,ConstantService::$response_fail);
            }

            $banner = $data['banner'];
            $tby = $data['tby'];
            unset($data['banner']);
            unset($data['tby']);

            $data['shop_id'] = $this->shop->id;
            $model = Goods::findOne(['id'=>$id]);
            $model->setAttributes($data);
            if($model->save()){

                //添加banner图
                if($id){
                    GoodsImg::deleteAll(['goods_id'=>$id]);
                }
                $newimg = [];
                for ($c = 0; $c < count($banner);$c++){
                    $imgdata = [];
                    $imgdata['goods_id'] = $id;
                    $imgdata['img_url'] = $banner[$c];
                    $imgdata['status'] = 1;
                    $imgdata['update_at'] = time();
                    $imgdata['create_at'] = time();
                    $newimg[] = $imgdata;
                }

                GoodsImg::getDb()->createCommand()->batchInsert('goods_img',['goods_id','img_url','status','update_at','create_at'],$newimg)->execute();

                foreach ($tby as $attrlist){
                    $setattr = array();
                    $goodsAttr = GoodsAttr::findOne(['id'=>$attrlist[5]]);
                    $setattr['goods_id'] = $id;
                    $setattr['original_price'] = $attrlist[0];
                    $setattr['discount_price'] = $attrlist[1];
                    $setattr['inventory'] = $attrlist[2];
                    $setattr['image'] = $attrlist[3]?$attrlist[3]:$data['list_img'];
                    $setattr['attribute_value_id'] = $attrlist[4];
                    $setattr['is_del'] = 0;
                    $setattr['update_time'] = time();
                    $goodsAttr->setAttributes($setattr);
                    $goodsAttr->save();
                }
                Active::updateAll(['goods_img'=>$data['list_img']],['status'=>[0,1],'is_del'=>0,'goods_id'=>$id]);

                //重新写入属性描述
                AttributeDeion::deleteAll(['goods_id'=>$id]);
                if(!empty($data['attr_describe'])) {
                    $this->_SetGoodsAttrDes($data['attr_describe'], $id);
                }
                return $this->renderJson([],'修改成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'修改失败',ConstantService::$response_success);
        }
        $googs_id = $this->get('id');
        if(!$googs_id){
            return $this->renderJson([],'缺少参数',ConstantService::$response_fail);
        } else {
            $is_shop = Goods::find()->where(['id' => $googs_id, 'shop_id' => $this->shop->id])->asArray()->one();
            if(!$is_shop){
                return $this->renderJson([],'没有此商品',ConstantService::$response_fail);
            }
        }

        $goods = Goods::find()->where(['id'=> $googs_id])->asArray()->one();

        $goodsimg = GoodsImg::find()->select('img_url')->where(['goods_id'=>$googs_id,'status'=>1])->asArray()->all();
        $goods['banner'] = $goodsimg;

        $googsattr = GoodsAttr::find()->where(['goods_id' => $googs_id,'is_del'=>0])->orderBy(['id'=>SORT_ASC])->asArray()->all();

        $onetree = Tree::find()->where(['pid'=>0])->asArray()->all();
        $twotree = Tree::find()->where(['pid'=>$goods['one_tree_id']])->asArray()->all();
        $threetree = Tree::find()->where(['pid'=>$goods['two_tree_id']])->asArray()->all();

        $attrlists = GoodsService::GetAttrlist($googs_id);
        $deion = AttributeDeion::find()
            ->select('id,key,val')
            ->where(['goods_id'=>$googs_id])
            ->asArray()
            ->all();
        return $this->render('update',[
            'onetree' => $onetree,
            'twotree' => $twotree,
            'threetree' => $threetree,
            'attrlist' => $attrlists,
            'goods' => $goods,
            'googsattr' => $googsattr,
            'attr_des' => $deion,
            'attr_count' => count($googsattr)
        ]);
    }


    /**
     * 删除
     */
    public function actionDelete(){
        if($this->isAjax()) {
            $id = $this->post('id');
            $Goods = Goods::find()->where(['shop_id' => $this->shop['id'], 'id' => $id])->asArray()->one();
            if ($Goods) {
                $newgoogs = Goods::findOne($id);
                $newgoogs->is_del = 1;
                $newgoogs->updated_at = time();
                if ($newgoogs->save()) {
                    $str = $this->shop->shop_name . '在' . date("Y-m-d H:i:s") . '删除商品' . $newgoogs['goods_name'];
                    LogaddService::logAdd($this->shop->shop_name, $str);
                    return $this->renderJson([], '删除成功', ConstantService::$response_success);
                }
                return $this->renderJson([], '删除失败', ConstantService::$response_fail);
            }
        }
        return $this->renderJson([],'参数不合法',ConstantService::$response_fail);
    }
    /**
     * 商品分类三级联动
     */
    public function actionGetTree(){
        $id = $this->post('id');
        $data = Tree::find()->where(['pid'=>$id])->asArray()->all();
        return $this->renderJson($data,'',ConstantService::$response_success);
    }

    /**
     * 是否在活动进行中
     */
    public function actionGetgoodss(){
        $id = $this->post('id');
        $data = Activity::find()->where(['goods_id'=>$id,'status'=>1])->asArray()->one();
        if($data){
            return $this->renderJson([],'活动进行中的商品不能修改',ConstantService::$response_fail);

        } else {
            return $this->renderJson([],'',ConstantService::$response_success);
        }
    }

    /**
     * 查看SKU
     */
    public function actionGetGoodsattr(){
        $id = $this->get('id');
        $list = GoodsService::GetAttrlist($id);
        return $this->renderJson($list,'',ConstantService::$response_success);
    }

    /**
     * 上下架
     */
    public function actionGoodsStatus(){
        if($this->isAjax()){
            $id = $this->post('id');
            if(!$id){
                $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $data = Goods::findOne(['id'=>$id]);

            if($data['status'] == 1){
                $data->status = 0;
            } else {
                $data->status = 1;
            }
            if($data->save()){
                $this->renderJson([],'修改成功',ConstantService::$response_success);
            }
        }
        $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 验证填入字段是否正确
     * @param array $data
     * @param bool $type
     * @return string
     */
    private function _validation($data = array()){
//        if(empty($data['three_tree_id'])){
//            return "请选择三级分类";
//        }
        if(empty($data['goods_name'])){
            return "商品名称不能为空";
        } else {
            $goods = Goods::find();
            $goods->andWhere(['goods_name'=>$data['goods_name']]);
            $goods->andWhere(['is_del'=>0]);
            $goods->andWhere(['shop_id'=>$this->shop['id']]);
            if(isset($data['goods_id'])){
                $goods->andWhere(['!=','id',$data['goods_id']]);
            }
            $goodsdata = $goods->asArray()->one();
            if(!empty($goodsdata)){
                return "商品名称已存在";
            }
        }
        if(empty($data['list_img'])){
            return "封面图不能为空";
        }
//        if(empty($data['content'])){
//            return "详情介绍不能为空";
//        }
        if($data['introduction']) {
            if (mb_strlen($data['introduction']) > 220) {
                return "商品描述不能超过220个字";
            }
        }

        return 'true';
    }

    /**
     * 添加商品属性描述
     */
    private function _SetGoodsAttrDes($data,$goodsId){
        $addData = [];
        foreach ($data as $val){
            $tmpdata['shop_id'] = $this->shop['id'];
            $tmpdata['goods_id'] = $goodsId;
            $tmpdata['key'] = $val['key'];
            $tmpdata['val'] = $val['val'];
            $tmpdata['create_time'] = time();
            $tmpdata['update_time'] = time();
            $addData[] = $tmpdata;
        }
        AttributeDeion::getDb()->createCommand()->batchInsert('attribute_deion',['shop_id','goods_id','key','val','create_time','update_time'],$addData)->execute();
    }
}